package com.dqyz.framework.aspectj;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import com.dqyz.busi.domain.Member;
import com.dqyz.busi.service.IMemberService;
import com.dqyz.common.core.domain.AjaxResult;
import com.dqyz.common.core.redis.RedisCache;
import com.dqyz.common.utils.ServletUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Aspect
@Order(-200)
@Component
public class NeedWechatLoginAspect {
    private static final Logger log =  LoggerFactory.getLogger(NeedWechatLoginAspect.class);

    public static ThreadLocal<Member> wechatLoginThreadLocal = new ThreadLocal<>();
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IMemberService memberService;
    @Pointcut("@annotation(com.dqyz.common.annotation.NeedWechatLogin)")
    public void performance() {
    }

    @Around("performance()")
    public Object watchPerformance(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            log.info("查看是否有小程序登录权限");
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            String wxToken = request.getHeader("wxToken");
            if (wxToken != null && !"".equals(wxToken)) {
                Member member = redisCache.getCacheObject(wxToken);
                if (member != null) {
                    Long id = member.getId();
                    member = memberService.selectMemberById(id);
                    wechatLoginThreadLocal.set(member);
                    return joinPoint.proceed();
                } else {
                    AjaxResult error = AjaxResult.error(401, "未登录或已经失效");
                    ServletUtil.write(response, JSONUtil.parse(error).toString(), "application/json;charset=utf-8");
                }
            } else {
                AjaxResult error = AjaxResult.error(401, "未登录或已经失效");
                ServletUtil.write(response, JSONUtil.parse(error).toString(), "application/json;charset=utf-8");
            }
            return null;
        } finally {
            wechatLoginThreadLocal.remove();
        }

    }

}
